package ld;

import ld.utils.JsonOut;
import ld.utils.MysqlUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;

@WebServlet(name = "RegServlet")
public class RegServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String email = request.getParameter("email");
        String psw = request.getParameter("password");
        String verify = request.getParameter("verify");

        HttpSession session = request.getSession();
        String captcha = session.getAttribute("validation_code").toString();
        PrintWriter out = response.getWriter();

        // 忽略大小写
        verify = verify.toLowerCase();
        captcha = captcha.toLowerCase();
        if (!verify.equals(captcha)){
            out.println(JsonOut.error(103, "verify"));
            return;
        }

        String savedPass = MysqlUtils.getPassword(email);
        if (savedPass != null){
            out.println(JsonOut.error(111, "email_exist"));
            return;
        }

        if (MysqlUtils.userRegister(email, psw))
            out.println(JsonOut.error(0, "reg_success"));
        else
            out.println(JsonOut.error(500, "reg_failed"));
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        PrintWriter out = response.getWriter();
        out.println(JsonOut.error(403, "forbidden"));
    }
}
